﻿#include "UdpServer.h"

#ifdef _WIN32 

bool UdpServer::Create(const Desc& desc)
{
	WSADATA wsa_data;
	if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0)
	{
		LOGI("WSAStartup() error!");
	}

	struct sockaddr_in serveraddr;

    if ((sock = socket(desc.af, desc.type, 0)) < 0) {
		perror("fail to socket");
		return 0;
	}

    LOGI("Create socket success");
    struct sockaddr_in addr;
    addr.sin_addr.S_un.S_addr = desc.sAddr;
	addr.sin_family = desc.sinFamily;
	addr.sin_port = htons(desc.port);

    if (SOCKET_ERROR == bind(sock, (struct sockaddr*)&addr, sizeof(struct sockaddr)))
	{
        LOGI("cannot bind %d",  desc.port);
        return 0;
	}

    LOGI("Create udp server listen on %d successfully", desc.port);

    return 1;
}

void UdpServer::Close()
{
    closesocket(sock);
	WSACleanup();

}
#endif // _WIN32


#ifdef __linux__
bool UdpServer::Create(const Desc &desc)
{
    struct sockaddr_in servaddr, cliaddr; // 定义服务器与客户端地址结构体
    socklen_t cliaddr_len;                // 客户端地址长度
    sock = socket(desc.af, desc.type, desc.protocol);
    if (sock == -1)
    {
        LOGI("socket failed return %d", socket);
        return false;
    }
    LOGI("Create socket success");

    servaddr.sin_family = desc.af;
    servaddr.sin_addr.s_addr = htonl(desc.sAddr);
    servaddr.sin_port = htons(desc.port);
    int bind_res = bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr));

    if (bind_res != 0)
    {
        LOGI("cannot bind %d", desc.port);
        return false;
    }

    LOGI("Create udp server listen on %d successfully", desc.port);

    return true;
}

void UdpServer::Close()
{
    close(sock);
}

#endif // DEBUG


